
import 'dart:io';
import 'dart:typed_data';

import 'package:logger/logger.dart';

import 'UploadAndDownloadDto.dart';

typedef void ErrorCallback(ErrorResult errorResult);
typedef void ReceiveData(List<int> data);

// socket 连接基础类
class ImSocket {

  final _logger = Logger(printer: PrettyPrinter(),);

  String ip;
  int port;
  ErrorCallback errorCallback = (ErrorResult errorResult)=>{};
  ReceiveData receiveData = (List<int> data)=> {}; // 接受数据回调

  late Socket _socket;
  bool _isConnected = false;

  ImSocket({ required this.ip, required this.port  });

  initData(ReceiveData receiveData, ErrorCallback errorCallback) {
    this.receiveData = receiveData;
    this.errorCallback = errorCallback;
  }

  bool isConnected() {
    return _isConnected;
  }

  connect() async {
    _socket = await Socket.connect(ip, port, timeout: const Duration(seconds: 60));
    _socket.listen(_receiveData, onError: _onError);
  }

  sendData(Uint8List data) async {
    _logger.i('imSocket write data, ${data.length}');
    if(data.isNotEmpty) {
      _socket.add(data);
    }
  }

  Future<void> close() async {
    _logger.i('imSocket close');
    await _socket.close();
  }

  void _receiveData(List<int> data) {
    _logger.i('imSocket receive data, ${data.length}');
    receiveData(data);
  }

  void _onError(error) {
    _logger.e('imSocket error, ${error}');
    errorCallback(ErrorResult('${error}'));
  }
}